$(function () {
    const registerModal = $("#registerModal");
    const email = $("#email");
    const passwd1 = $("#password_res");
    const passwd2 = $("#password_res_again");
    const registerBtn = $("#register");
    const register_sign_div = $("#register_sign_div");
    const register_sign = $("#register_sign");
    const preference = $('#preference');

    registerBtn.on("click", function () {
        if (email.val() === "") {
            register_sign_div.show();
            register_sign.val("请设置邮箱").css({'color': 'red'});
        }
        else if (passwd1.val() === "") {
            register_sign_div.show();
            register_sign.val("请设置密码").css({'color': 'red'});
        }
        else if (passwd2.val() === "") {
            register_sign_div.show();
            register_sign.val("请再次输入密码").css({'color': 'red'});
        }
        else if (passwd1.val() !== "" && passwd2.val() !== "" && passwd1.val() != passwd2.val()) {
            register_sign_div.show();
            register_sign.val("输入密码不一致，请重新输入").css({'color': 'red'});
        } else {
            $.post('/users/signup', {
                username: email.val(),
                password: passwd1.val(),
                preference: preference.val()
            }, function (res) {
                if (res && res.error) {
                    register_sign_div.show();
                    register_sign.val(res.error.message).css({color: 'red'});
                } else if (res && res.success) {
                    location.reload();
                }
            });
        }
    });
    registerModal.keyup(function (e) {
        if (e.keyCode == 13) {
            registerBtn.click();
        }
    });

    email.on("focus", function () {
        register_sign_div.hide();
    });

    passwd1.on("focus", function () {
        register_sign_div.hide();
    });

    passwd2.on("focus", function () {
        register_sign_div.hide();
    });
});